package asn.match.dao;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import asn.match.model.Profil;
import asn.match.security.MyUtils;

@Service("profil")
@PersistenceContext(type = PersistenceContextType.EXTENDED)
@Transactional
public class ProfilDaoImpl implements ProfilDAO {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public void addProfil(Profil profil) {
		Date date = new Date();
		Timestamp created_at = new Timestamp(date.getTime());
		String ipAdress = MyUtils.getIpAddress();
		profil.setIpAdress(ipAdress.toString());
		profil.setStatus("to_complete");
		profil.setCreatedAt(created_at);
		profil.setModifiedAt(created_at);
		this.sessionFactory.getCurrentSession().save(profil);
		
	}

	@Override
	public void updateProfil(Profil profil) {
		Date date = new Date();
		Timestamp modified_at = new Timestamp(date.getTime());
		profil.setModifiedAt(modified_at);
		this.sessionFactory.getCurrentSession().saveOrUpdate(profil);
	}

	@Override
	public void deleteProfil(Profil profil) {
		this.sessionFactory.getCurrentSession().delete("profil", profil);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Profil> findAllProfils() {
		return (List<Profil>) this.sessionFactory.getCurrentSession().createQuery("from Profil profil").list();
		}

	@Override
	public Profil findProfilById(Integer profilId) {
		return (Profil) this.sessionFactory.getCurrentSession().get(Profil.class, profilId);
	}

}
